<template>
    <ych-modal
      :fullscreen="false"
      :title="title"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
      :cancelText="$t('m.common.button.close')">

      <a-spin :spinning="confirmLoading">
        <a-form :form="form">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="menuLabel"
            >
            <a-input v-decorator="[ 'name', validatorRules.name]" :readOnly="disableSubmit">
            </a-input>
          </a-form-item>
	        <a-form-item
            v-show="lang_enable"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="$t('m.system.permission.entity.zhCn')"
            >
            <a-input v-model="zhCn" :readOnly="disableSubmit"/>
          </a-form-item>
          <a-form-item
            v-show="lang_enable"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="$t('m.system.permission.entity.enUs')"
            >
            <a-input v-model="enUs" :readOnly="disableSubmit"/>
          </a-form-item>
         <!-- <a-form-item
            v-show="lang_enable"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="$t('m.system.permission.entity.language1')"
            >
            <a-input v-model="language1" :readOnly="disableSubmit"/>
          </a-form-item>
          <a-form-item
            v-show="lang_enable"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="$t('m.system.permission.entity.language2')"
            >
            <a-input v-model="language2" :readOnly="disableSubmit"/>
          </a-form-item>
          <a-form-item
            v-show="lang_enable"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="$t('m.system.permission.entity.language3')"
            >
            <a-input v-model="language3" :readOnly="disableSubmit"/>
          </a-form-item>-->
	        <a-form-item v-show="this.model.topFlag!=1"  :label="$t('m.system.permission.entity.menuType')" :labelCol="labelCol" :wrapperCol="wrapperCol">
	          <a-radio-group @change="onChangeMenuType" v-decorator="['menuType',{'initialValue':localMenuType}]" button-style="solid">
              <a-radio-button :value="1">{{$t('m.system.permission.other.permission_type2')}}</a-radio-button>
              <a-radio-button :value="2">{{$t('m.system.permission.other.permission_type3')}}</a-radio-button>
              </a-radio-group>
          </a-form-item>

          <a-form-item v-show="this.model.topFlag===1" :label="$t('m.system.permission.entity.menuType')" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-radio-group @change="onChangeMenuType" v-decorator="['menuType',{'initialValue':localMenuType}]" button-style="solid">
              <a-radio-button :value="0">{{$t('m.system.permission.other.permission_type1')}}</a-radio-button>
              <a-radio-button :value="1">{{$t('m.system.permission.other.permission_type2')}}</a-radio-button>
            </a-radio-group>
          </a-form-item>

          <a-form-item
            v-show="this.model.topFlag===0"
            :label="$t('m.system.permission.entity.parentId')"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :validate-status="validateStatus"
            :hasFeedback="true"
            :required="true">
            <span slot="help">{{ validateStatus==='error'?proMenuMsg:'&nbsp;&nbsp;' }}</span>
            <a-tree-select
              style="width:100%"
              :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
              :treeData="treeData"
              v-model="model.parentId"
              placeholder=""
              :disabled="disableSubmit"
              @change="handleParentIdChange">
            </a-tree-select>
          </a-form-item>

          <a-form-item
            v-show="this.model.topFlag===1 && this.model.menuType === 1"
            :label="$t('m.system.permission.entity.parentId')"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :validate-status="validateStatus"
            :hasFeedback="true"
            :required="true">
            <span slot="help">{{ validateStatus==='error'?proMenuMsg:'&nbsp;&nbsp;' }}</span>
            <a-tree-select
              style="width:100%"
              :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
              :treeData="commonFrontMenu"
              v-model="model.parentId"
              placeholder=""
              :disabled="disableSubmit"
              @change="handleParentIdChange">
            </a-tree-select>
          </a-form-item>

          <a-form-item
            v-show="show"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="$t('m.system.permission.entity.url')">
            <a-input placeholder="" v-decorator="[ 'url',validatorRules.url]" :readOnly="disableSubmit">
              <app-menu-url-tag v-show="this.model.menuType===1 && this.model.topFlag!=1" slot="addonAfter" style="width: 130px" :placeholder="$t('m.system.permission.other.select_component')" :groupId="groupId" @change="handleChangeUrl"></app-menu-url-tag>
            </a-input>
          </a-form-item>

          <a-form-item
            v-show="show"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="$t('m.system.permission.entity.component')">
            <a-input placeholder="" v-decorator="[ 'component',validatorRules.component]"
                     :readOnly="disableSubmit" @change="handleChangeComponentName">
              <a-select slot="addonAfter" style="width: 100px" @change="handleChangeComponent"
                        v-model="componentSelectValue" :placeholder="$t('m.system.permission.other.select_component')">
                <a-select-option value="eform/redirect/FormRedirectAddTab">
                  {{$t('m.system.permission.other.form_component')}}
                </a-select-option>
                <a-select-option value="bpm/redirect/RedirectAddTab">
                  {{$t('m.system.permission.other.flow_component')}}
                </a-select-option>
                <a-select-option value="eform/redirect/ReportWidgetRedirectCard">
                  {{$t('m.system.permission.other.report_component')}}
                </a-select-option>
                <a-select-option value="eform/redirect/ViewLayoutRedirect">
                  {{$t('m.system.permission.other.view_component')}}
                </a-select-option>
                <a-select-option value="layouts/RouteView">
                  {{$t('m.system.permission.other.route_component')}}
                </a-select-option>
                <a-select-option value="layouts/IframePageView">
                  {{$t('m.system.permission.other.iframe_component')}}
                </a-select-option>
                <a-select-option value="layouts/MicroAppFrame">
                  {{$t('m.system.permission.other.microApp_component')}}
                </a-select-option>
              </a-select>
            </a-input>
          </a-form-item>
          <a-form-item
            v-show="show"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="$t('m.system.permission.entity.componentProps')">
            <KChangeOption v-model="componentProps" :readOnly="disableSubmit" :placeholder-label="$t('m.common.label.parameter_key')" :placeholder-value="$t('m.common.label.parameter_value')" :group-id="groupId"/>
          </a-form-item>

<!--          <a-form-item
            v-show="model.menuType==='0'"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="默认跳转地址">
            <a-input placeholder="请输入路由参数 redirect" v-decorator="[ 'redirect',{}]" :readOnly="disableSubmit"/>
          </a-form-item>-->

          <a-form-item
            v-show="!show"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="$t('m.system.permission.entity.perms')">
            <a-input :placeholder="this.$t('m.system.permission.other.perms_placeholder')"
                     v-decorator="[ 'perms', {rules:[{ required: false, message: this.$t('m.system.permission.verify.perms') },{validator: this.validatePerms }]}]"
                     :readOnly="disableSubmit"/>
          </a-form-item>

          <a-form-item
            v-show="!show"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="$t('m.system.permission.entity.permsType')">
            <ych-dict-select-tag v-decorator="['permsType', {}]" placeholder="" :type="'radio'"
                               :triggerChange="true" dictCode="global_perms_type"/>

          </a-form-item>
          <a-form-item
            v-show="!show"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="$t('m.system.permission.entity.status')">
            <ych-dict-select-tag v-decorator="['status', {}]" placeholder="" :type="'radio'" :triggerChange="true"
                               dictCode="valid_status"/>
          </a-form-item>

          <a-form-item
            v-show="show"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="$t('m.system.permission.entity.icon')">
            <ych-icon-select v-model="model.icon" :disabled="disableSubmit" write :iconfont="true"></ych-icon-select>
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="$t('m.system.permission.entity.back_show')">
            <a-switch :checkedChildren="$t('m.common.label.yes')" :unCheckedChildren="this.$t('m.common.label.no')" v-model="back" @change="loadCommonFrontMenu"/>
          </a-form-item>

          <a-form-item
            v-show="show"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="$t('m.system.permission.entity.sortNo')">
            <a-input-number placeholder="" style="width: 200px" v-decorator="[ 'sortNo',validatorRules.sortNo]"
                            :readOnly="disableSubmit"/>
          </a-form-item>

          <a-form-item
            v-show="show"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="$t('m.system.permission.entity.menuHidden')">
            <a-radio-group v-model="menuHidden" button-style="solid">
              <a-radio-button :value=true>{{this.$t('m.common.label.yes')}}</a-radio-button>
              <a-radio-button :value=false>{{this.$t('m.common.label.no')}}</a-radio-button>
            </a-radio-group>
          </a-form-item>

          <a-form-item
            v-show="show && componentName && componentName !== 'layouts/RouteView'"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="$t('m.system.permission.entity.isKeepalive')">
            <a-radio-group v-model="isKeepalive" button-style="solid">
              <a-radio-button :value=true>{{this.$t('m.common.label.yes')}}</a-radio-button>
              <a-radio-button :value=false>{{this.$t('m.common.label.no')}}</a-radio-button>
            </a-radio-group>
          </a-form-item>

          <a-form-item
            v-show="show && componentName === 'layouts/IframePageView'"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="$t('m.system.permission.entity.internalOrExternal')">
            <a-radio-group v-model="internalOrExternal" button-style="solid">
              <a-radio-button :value=true>{{this.$t('m.common.label.yes')}}</a-radio-button>
              <a-radio-button :value=false>{{this.$t('m.common.label.no')}}</a-radio-button>
            </a-radio-group>
          </a-form-item>

          <!-- 微前端应用-->
          <a-form-item
            v-show="show && componentName === 'layouts/MicroAppFrame'"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="$t('m.system.permission.entity.microApp_url')">
            <a-input v-decorator="[ 'microAppUrl',validatorRules.microAppUrl]" :readOnly="disableSubmit"/>
          </a-form-item>
<!--          <a-form-item
            v-show="show && componentName === 'layouts/MicroAppFrame'"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="$t('m.system.permission.entity.microApp_route')">
            <a-input v-decorator="[ 'microAppRoute',validatorRules.microAppRoute]" :readOnly="disableSubmit"/>
          </a-form-item>-->

        </a-form>
      </a-spin>

  </ych-modal>
</template>

<script>

  import { addPermission, editPermission,duplicateCheck } from '@/api/api'
  import { getAction } from '@/api/manage'
  import AppMenuUrlTag from '../select/tag/AppMenuUrlTag'
  import { getFormUrl,getFlowUrl,getViewUrl,getWidgetUrl } from '@/utils/hbdUtil'
  import YchConstant from "@/api/YchConstant";
  import {YchIconSelect} from '@yuncheng/ych-components'
  import KChangeOption from "./designer/packages/KChangeOption";

  export default {
    name: 'ActAppPermissionModal',
    components: {
      AppMenuUrlTag,
      YchIconSelect,
      KChangeOption,
    },
    props:{
      category:{
        type:String
      },
      groupId:{
        type:String
      }
    },
    data () {
      return {
        drawerWidth: 700,
        treeData: [],
        commonFrontMenu:[],//前台公共菜单
        treeValue: '0-0-4',
        title: this.$t('m.common.label.operate'),
        visible: false,
        disableSubmit: false,
        model: {},
        localMenuType: 1,
        alwaysShow: false,//表单元素-聚合路由
        menuHidden: false,//表单元素-隐藏路由
        internalOrExternal: false,//菜单打开方式
        isKeepalive: true, //是否缓存路由
        componentProps: [],
        back:false,//是否后端菜单
        show: true,//根据菜单类型，动态显示隐藏表单元素
        zhCn:"",//国际化-中文
        enUs:"",//国际化-英文
        language1:"",//国际化-扩展语言1
        language2:"",//国际化-扩展语言2
        language3:"",//国际化-扩展语言3
        menuLabel: this.$t('m.system.permission.other.permission_type0'),
        isRequrie: true,  // 是否需要验证
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        form: this.$form.createForm(this),
        validateStatus: '',
        componentSelectValue: undefined,
        componentName: null,
        proMenuMsg: this.$t('m.eform.formDesign.label.qing-xuan-ze-shang-ji-cai-dan'),
        lang_enable: bootConfig[process.env.NODE_ENV].VUE_APP_LOCALE_ENABLE
      }
    },
    computed: {
      validatorRules: function () {
        const isMicroApp = this.show && this.componentName === 'layouts/MicroAppFrame';
        return {
          name: { rules: [{ required: true, message: this.$t('m.system.permission.verify.name') }] },
          component: { rules: [{ required: this.show, message: this.$t('m.system.permission.verify.component') }] },
          url: { rules: [{ required: this.show, message: this.$t('m.system.permission.verify.url') }] },
          permsType: { rules: [{ required: true, message: this.$t('m.system.permission.verify.permsType') }] },
          sortNo: { initialValue: 1.0 },
          microAppRoute: {},
          microAppUrl: {rules: [{ required: isMicroApp, message: this.$t('m.system.permission.verify.microApp_url') }]},
        }
      }
    },
    created () {
      this.initDictConfig()
    },
    methods: {
      loadTree () {
        var that = this
        let params = {category:this.category,groupId:this.groupId}
        getAction(YchConstant.PREFIX_SYSTEM + "/permission/queryAppTreeList",params).then((res) => {
          if (res.success) {
            that.treeData = []
            let treeList = res.result.treeList
            for (let a = 0; a < treeList.length; a++) {
              let temp = treeList[a]
              temp.isLeaf = temp.leaf
              that.treeData.push(temp)
            }
          }
        })
      },
      loadCommonFrontMenu () {
        var that = this
        let params = {
          back: this.back ? "1" : "0"
        }
        getAction(YchConstant.PREFIX_SYSTEM + "/permission/queryFrontCommonTreeList",params).then((res) => {
          if (res.success) {
            that.commonFrontMenu = []
            let treeList = res.result.treeList
            for (let a = 0; a < treeList.length; a++) {
              let temp = treeList[a]
              temp.isLeaf = temp.leaf
              that.commonFrontMenu.push(temp)
            }
          }
        })
      },
      add() {
        // 默认值
        this.edit({
          status: '1',
          permsType: '1',
          route: true,
          keepAlive: true,
          category: this.category,
          groupId: this.groupId,
          menuType: 1,
          topFlag: 0
        })
      },
      edit (record) {
        this.form.resetFields()
        this.model = Object.assign({}, record)
        //--------------------------------------------------------------------------------------------------
        //根据菜单类型，动态展示页面字段
        this.back = !!record.back
        this.alwaysShow = !!record.alwaysShow
        this.menuHidden = !!record.hidden

        this.isKeepalive = !!record.keepAlive

        this.componentProps = record.componentProps ? JSON.parse(record.componentProps) : []

        this.internalOrExternal = !!record.internalOrExternal

        this.show = record.menuType !== 2
        this.menuLabel = record.menuType === 2 ? this.$t('m.system.permission.other.permission_type3') : this.$t('m.system.permission.other.permission_type0')

        this.enUs = record.enUs
        this.zhCn = record.zhCn
        this.language1 = record.language1
        this.language2  = record.language2
        this.language3= record.language3
        //----------------------------------------------------------------------------------------------

        this.visible = true
        if(record.topFlag===1){
          this.loadCommonFrontMenu()
        }else{
          this.loadTree()
        }

        let fieldsVal = this.lodash.pick(this.model, 'name', 'perms', 'permsType', 'component', 'url', 'sortNo', 'menuType', 'status', 'microAppUrl')
        this.$nextTick(() => {
          this.form.setFieldsValue(fieldsVal)
          this.componentName = this.model.component;
        })
      },
      close () {
        this.$emit('close')
        this.disableSubmit = false
        this.visible = false
      },
      handleOk () {
        const that = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            this.model.back = this.back;
            this.model.alwaysShow = this.alwaysShow
            this.model.hidden = this.menuHidden
            this.model.keepAlive = this.isKeepalive
            this.model.componentProps = JSON.stringify(this.componentProps)
            this.model.internalOrExternal = this.internalOrExternal
            this.model.zhCn = this.zhCn
            this.model.enUs = this.enUs
            this.model.language1 = this.language1
            this.model.language2 = this.language2
            this.model.language3 = this.language3


            let formData = Object.assign(this.model, values)
            if ((formData.menuType === 1 || formData.menuType === 2) && !formData.parentId) {
              that.validateStatus = 'error'
              that.messageUtil.error(this.$t('m.system.permission.verify.menuType'))
              return
            } else {
              that.validateStatus = 'success'
            }
            that.confirmLoading = true
            //console.log(formData)
            let obj
            if (!this.model.id) {
              obj = addPermission(formData)
            } else {
              obj = editPermission(formData)
            }
            obj.then((res) => {
              if (res.success) {
                that.messageUtil.success(res.message)
                that.$emit('ok')
              } else {
                that.messageUtil.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
              that.close()
            })
          }
        })
      },
      handleCancel () {
        this.close()
      },
      validateNumber (rule, value, callback) {
        if (!value || new RegExp(/^[0-9]*[1-9][0-9]*$/).test(value)) {
          callback()
        } else {
          callback(this.$t('m.system.permission.verify.number'))
        }
      },
      validatePerms (rule, value, callback) {
        if (value && value.length > 0) {
          //校验授权标识是否存在
          var params = {
            tableName: 'sys_permission',
            fieldName: 'perms',
            fieldVal: value,
            dataId: this.model.id
          }
          duplicateCheck(params).then((res) => {
            if (res.success) {
              callback()
            } else {
              callback(this.$t('m.system.permission.verify.duplicate_perms'))
            }
          })
        } else {
          callback()
        }
      },
      onChangeMenuType (e) {
        this.model.menuType = e.target.value
        this.localMenuType = e.target.value
        if (e.target.value === 2) {
          this.show = false
          this.menuLabel =  this.$t('m.system.permission.other.permission_type3')
        } else {
          this.show = true
          this.menuLabel = this.$t('m.system.permission.other.permission_type0')
        }
        if(this.model.topFlag ===1){
          if(e.target.value === 0){
            this.model.parentId = ''
          }
        }
        // this.$nextTick(() => {
        //   this.form.validateFields(['url', 'component'], { force: true })
        // })
      },
      // 根据屏幕变化,设置抽屉尺寸
      resetScreenSize () {
        let screenWidth = document.body.clientWidth
        if (screenWidth < 500) {
          this.drawerWidth = screenWidth
        } else {
          this.drawerWidth = 700
        }
      },
      initDictConfig () {
      },
      handleParentIdChange (value) {
        if (!value) {
          this.validateStatus = 'error'
        } else {
          this.validateStatus = 'success'
        }
      },
      handleChangeComponent (value) {
        this.form.setFieldsValue({ component: value })
        this.componentName = value;
        this.componentSelectValue = undefined
      },
      handleChangeUrl(value, type, label) {
        if (!value) return
        const fieldsValue = {}
        // 设置菜单名称
        const values = this.form.getFieldsValue(["name"])
        if (!values.name) {
          fieldsValue["name"] = label[0]
        }
        if (type === 'form') {
          fieldsValue["url"] = getFormUrl(value)
          fieldsValue["component"] = 'eform/redirect/FormRedirectAddTab'
        } else if (type === 'view') {
          fieldsValue["url"] = getViewUrl(value)
          fieldsValue["component"] = 'eform/redirect/ViewLayoutRedirect'
        } else if (type === 'process') {
          fieldsValue["url"] = getFlowUrl(value)
          fieldsValue["component"] = 'bpm/redirect/RedirectAddTab'
        } else if (type === 'report') {
          fieldsValue["url"] = getWidgetUrl(value)
          fieldsValue["component"] = 'eform/redirect/ReportWidgetRedirectCard'
        }
        this.form.setFieldsValue(fieldsValue)
        this.componentName = fieldsValue["component"]
      },
      handleChangeComponentName(){
        this.$nextTick(() => {
          this.componentName = this.form.getFieldValue('component')
        })
      }
    }
  }
</script>
